<template>
  <div>
    <q-btn
        class="btn margin-l-20 margin-b-20"
        label="新增"
        color="primary"
        unelevated
        @click="addApplication"/>
    <q-table
        :data="tableData"
        :columns="columns"
        row-key="id"
        style="height: 320px"
        class="myTable scroll stick-last-col"
        :loading="isTableLoading"
        :hide-bottom="tableData.length > 0"
        color="primary"
    >
      <template v-slot:body-cell-operations="props">
        <q-td class="operations" style="width: 180px">
          <div class="btn-group" style="text-align: center">

            <q-btn flat color="primary" class="qa-d-text" v-throttle label="升级"
                   :disable="isPreVersion"
                   @click="upgrade(props.row)"
            />
            <q-btn flat color="primary" class="qa-d-text" v-throttle label="编辑"
                   :disable="isPreVersion || props.row.editDisable"
                   @click="editApplication(props.row)"
            />
            <q-btn flat color="primary" class="qa-d-text" v-throttle label="配置"
                   :disable="isPreVersion || props.row.editDisable"
                   @click="editConfig(props.row)"
            />
            <q-btn flat color="primary" class="qa-d-text" v-throttle label="删除"
                   :disable="isPreVersion"
                   @click="deleteApp(props.row)"
            />
          </div>
        </q-td>
      </template>
    </q-table>
    <ApplicationAddEditDialog ref="applicationAddEditDialog"
                              :driverList="driverList"
                              @submit="submitApp"
                              :submitting="submitting"
                              :bindApp="tableData"/>

    <ConfigEditDialog ref="configEditDialog" @submit="submitConfig" :submitting="submitting"/>

  </div>
</template>

<script>
import ApplicationAddEditDialog from './application-detail/application-add-edit-dialog.vue'
import ConfigEditDialog from './application-detail/config-edit-dialog.vue'
import {
  boxAppRemove,
  boxBindApp,
  boxEditApp, editAppConfig,
  getBoxApplicationQuery,
  upgradeUcloudUpApplication
} from '../../../../boot/miot/plc-list'

export default {
  name: 'application-info',
  components: {
    ApplicationAddEditDialog,
    ConfigEditDialog
  },
  props: {
    boxId: {
      type: String,
      default: ''
    },
    isPreVersion: {
      type: Boolean,
      default: false
    },
    driverList: {
      type: Array,
      default: () => []
    },
    detailDriverParams: {
      type: Object,
      default: () => {
      }
    }
  },
  watch: {
    boxId: {
      immediate: true,
      handler (val) {
        if (val) {
          this.getTableData()
        }
      }
    }
  },
  data () {
    return {
      tableData: [],
      columns: [
        { name: 'applicationName', label: '应用名称', align: 'left', field: 'applicationName' },
        { name: 'description', label: '应用描述', align: 'left', field: 'description' },
        { name: 'version', label: '应用版本', align: 'left', field: 'version' },
        { name: 'versionDescription', label: '版本描述', align: 'left', field: 'versionDescription' },
        { name: 'applicationType', label: '应用类型', align: 'left', field: 'applicationType' },
        { name: 'onlineStatusName', label: '运行状态', align: 'left', field: 'onlineStatusName' },
        { name: 'relativeDriver', label: '关联驱动', align: 'left', field: 'relativeDriver' },
        { name: 'operations', label: '操作', align: 'center', field: 'operations' }
      ],
      isTableLoading: false,
      edgeApplicationID: '',
      submitting: false
    }
  },
  methods: {
    getTableData () {
      getBoxApplicationQuery(this.boxId).then(res => {
        const { data } = res
        const statusObj = {
          'unreported': '-',
          'online': '在线',
          'offline': '离线'
        }
        data.forEach(item => {
          const drivers = item.drivers
          let relativeDriver = ''
          drivers.forEach((item, index) => {
            if (index !== 0) {
              relativeDriver += ','
            }
            relativeDriver += item.driverName
          })
          item.relativeDriver = relativeDriver
          item.onlineStatusName = item.onlineStatus ? statusObj[item.onlineStatus] : ''
          item.editDisable = item.applicationName.startsWith('Horseman') || item.applicationName.indexOf('DLP_APP') > -1
        })
        this.tableData = data
      })
    },
    upgrade (info) {
      if (this.isPreVersion) {
        return
      }
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要升级吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        const params = {
          applicationID: info.applicationID,
          edgeApplicationID: info.edgeApplicationID
        }
        upgradeUcloudUpApplication(params).then(res => {
          this.$message.success('升级成功')
          this.getTableData()
        })
      })
    },

    // 打开新增应用
    addApplication () {
      this.$refs.applicationAddEditDialog.showDialog()
    },
    // 打开新增应用
    editApplication (data) {
      const info = {
        application: data.applicationID,
        version: data.version,
        deviceDriverIds: data.drivers.map(item => item.id)
      }
      this.edgeApplicationID = data.edgeApplicationID
      this.$refs.applicationAddEditDialog.showDialog(info)
    },
    // 提交应用
    submitApp (info) {
      const data = {
        gatewayId: this.detailDriverParams.gatewayId,
        productId: this.detailDriverParams.productId,
        ucloudBoxNum: this.detailDriverParams.ucloudBoxNum,
        applicationID: info.applicationID,
        applicationName: info.applicationName,
        deviceDriverIds: info.deviceDriverIds,
        version: info.version
      }
      const configData = {
        config: info.config,
        applicationName: info.applicationName,
        version: info.version,
        appId: data.applicationID
      }
      this.submitting = true
      if (info.isEdit) {
        boxEditApp(data).then(res => {
          this.edgeApplicationID = res.data
          this.$refs.applicationAddEditDialog.hideDialog()
          this.getTableData()
        }).finally(() => {
          this.submitting = false
        })
      } else {
        boxBindApp(data).then(res => {
          this.edgeApplicationID = res.data
          this.getTableData()
          this.$refs.applicationAddEditDialog.hideDialog()
          this.$refs.configEditDialog.showDialog(configData)
        }).finally(() => {
          this.submitting = false
        })
      }
    },
    // 删除应用
    deleteApp (row) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要删除吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        const data = {
          applicationID: row.applicationID,
          applicationName: row.applicationName,
          gatewayId: this.detailDriverParams.gatewayId,
          productId: this.detailDriverParams.productId,
          ucloudBoxNum: this.detailDriverParams.ucloudBoxNum
        }
        boxAppRemove(data).then(res => {
          this.$message.success('删除成功')
          this.getTableData()
        })
      })
    },
    // 配置
    editConfig (row) {
      this.edgeApplicationID = row.edgeApplicationID
      const data = {
        config: row.config,
        applicationName: row.applicationName,
        version: row.version,
        appId: row.applicationID
      }
      this.$refs.configEditDialog.showDialog(data)
    },
    // 提交编辑
    submitConfig (config) {
      const data = {
        edgeApplicationID: this.edgeApplicationID,
        config
      }
      editAppConfig(data).then(() => {
        this.$message.success('配置成功')
        this.$refs.configEditDialog.hideDialog(data)
        this.getTableData()
      })
    }
  }
}
</script>

<style scoped>

</style>
